<template>
  <d2-container class="page">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="用户设置" name="userInfo">
        <el-form
      v-loading="loading"
      ref="userInfoForm"
      :model="userInfo"
      required-asterisk
      center
    >
    <el-row>
      <el-col :span="6" :push="1">
        <UploadImg v-model="userInfo.avatar"/>
      </el-col>
      <el-col :span="10" :pull="1">
        <el-form-item prop="nickName" required label="昵称">
        <el-input v-model="userInfo.nickName" clearable></el-input>
      </el-form-item>
      </el-col>
      <el-col :span="10" :pull="1">
        <el-form-item label="电话号码" prop="phoneNumber">
        <el-input v-model="userInfo.phoneNumber" clearable></el-input>
      </el-form-item>
      </el-col>

    </el-row>
    <el-row>
      <el-col :span="10" :offset="6" :pull="1">
        <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="10" :offset="6" :pull="1">
        <el-form-item label="性別" prop="gender">
        <el-radio-group v-model="userInfo.gender">
          <el-radio
            v-for="item in genderOptions "
            :key="Number(item.value)"
            :label="Number(item.value)"
          >{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      </el-col>
      <el-col :span="10" :offset="6" :pull="1">
          <el-form-item>
        <el-button @click="updateInfo" type="primary" :loading="updateInfoLoading">
          <i class="fa fa-check"></i>
          更新
        </el-button>
        <el-button @click="resetForm('info')" type="info">
          <i class="fa fa-reply-all"></i>
          重置
        </el-button>
      </el-form-item>
      </el-col>
    </el-row>
    </el-form>
    </el-tab-pane>
      <el-tab-pane label="密码设置" name="password">
        <el-row :gutter="20">
          <el-col :span="10" :offset="6">
            <el-form
              ref="userPasswordForm"
              :model="userPasswordInfo"
              required-asterisk
              :label-position="position"
              :rules="passwordRules"
              center
            >
              <el-form-item label="原密码" required prop="oldPassword">
                <el-input v-model="userPasswordInfo.oldPassword" clearable></el-input>
              </el-form-item>
              <el-form-item required prop="newPassword" label="新密码">
                <el-input type="password" v-model="userPasswordInfo.newPassword" clearable></el-input>
              </el-form-item>
              <el-form-item required prop="newPassword2" label="确认密码">
                <el-input type="password" v-model="userPasswordInfo.newPassword2" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="settingPassword" :loading="settingPasswordLoading">
                  <i class="fa fa-check"></i>提交
                </el-button>
                <el-button @click="resetForm('passwordForm')" type="info">
                  <i class="fa fa-reply-all"></i>重置
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </d2-container>
</template>
<script>
import util from '@/libs/util.js'
import { mapActions, mapState } from 'vuex'
import { MessageBox } from 'element-ui'
import { title } from 'faker/lib/locales/zh_CN'
import UploadImg from '../upload_image'
export default {
  components: {
    UploadImg
  },
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value === this.userPasswordInfo.oldPassword) {
        callback(new Error('原密码与新密码一致'))
      } else {
        if (this.userPasswordInfo.newPassword2 !== '') {
          this.$refs.userPasswordForm.validateField('newPassword2')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.userPasswordInfo.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      settingPasswordLoading: false,
      updateInfoLoading: false,
      loading: true,
      genderOptions: [],
      position: 'left',
      activeName: 'userInfo',
      userInfo: {
        nickName: '',
        gender: 1,
        phoneNumber: '',
        avatar: '',
        email: ''
      },
      userInforules: {
        nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      },
      userPasswordInfo: {
        oldPassword: '',
        newPassword: '',
        newPassword2: ''
      },
      passwordRules: {
        oldPassword: [
          {
            required: true,
            message: '请输入原密码',
            trigger: 'blur'
          }
        ],
        newPassword: [{ validator: validatePass, trigger: 'blur' }],
        newPassword2: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  mounted () {
    this.getCurrentUserInfo()
    this.initDict()
  },
  computed: {
    ...mapState('d2admin/user', [
      'info'
    ])
  },
  methods: {
    initDict () {
      const _self = this
      _self.genderOptions = util.dict.getDictValue('sys_user_gender')
    },
    ...mapActions('d2admin/user', [
      'userInfoById',
      'userUpdate',
      'updatePassword',
      'set'
    ]),
    ...mapActions('d2admin/account', ['logout']),
    /**
     * 获取当前用户信息
     */
    getCurrentUserInfo () {
      const _self = this
      _self.loading = true
      const userId = util.cookies.get('uuid')
      if (userId) {
        _self.userInfoById({ data: { id: userId } }).then((result) => {
          _self.userInfo = result.userInfo
          _self.loading = false
        })
      }
    },
    /**
     * 更新用户信息
     */
    updateInfo () {
      const _self = this
      _self.$refs.userInfoForm.validate((valid) => {
        if (valid) {
          const userId = util.cookies.get('uuid')
          if (userId) {
            const info = JSON.parse(JSON.stringify(_self.userInfo))
            const params = {
              id: userId,
              nickName: info.nickName,
              email: info.email,
              phoneNumber: info.phoneNumber,
              gender: info.gender,
              avatar: info.avatar
            }
            _self.updateInfoLoading = true
            _self
              .userUpdate({ data: params })
              .then((result) => {
                this.$message.success('修改成功')
                _self.getCurrentUserInfo()
                _self.set({
                  name: info.nickName,
                  avatar: info.avatar
                })
                _self.updateInfoLoading = false
              })
          }
        } else {
          // 校验失败
          // 登录表单校验失败
          this.$message.error('表单校验失败，请检查')
        }
      })
    },
    resetForm (name) {
      const _self = this
      if (name === 'info') {
        _self.getCurrentUserInfo()
      } else {
        _self.userPasswordForm = {}
      }
    },
    handleClick (tab, event) {
      const _self = this
      if (tab.paneName === 'userInfo') {
        // 表单数据清空
        _self.$refs.userPasswordForm.resetFields()
        // 执行重置按钮事件
        _self.resetForm('info')
      } else {
        _self.$refs.userInfoForm.resetFields()
      }
    },
    /**
     * 重新设置密码
     */
    settingPassword () {
      const _self = this
      _self.$refs.userPasswordForm.validate((valid) => {
        if (valid) {
          const userId = util.cookies.get('uuid')
          if (userId) {
            const params = JSON.parse(JSON.stringify(_self.userPasswordInfo))
            _self.settingPasswordLoading = true
            _self
              .updatePassword({ data: { id: userId, params } })
              .then((result) => {
                _self.activeName = 'userInfo'
                _self.settingPasswordLoading = false
                _self.logout()
              })
          }
        } else {
          // 校验失败
          // 登录表单校验失败
          this.$message.error('表单校验失败，请检查')
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.userInfo.avatar = URL.createObjectURL(file.raw)
      console.log(this.userInfo.avatar)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>
<style scoped>

</style>
